import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { indexOf } from 'lodash';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  message,
  Popconfirm,
  Tabs,
  Table,
  Dropdown,
  Menu,
  notification,
  Alert,
  Icon,
} from 'antd';

const TabPane = Tabs.TabPane;
import { convertProjectCode } from './components/toolkit';
import MatchScoreForm from './components/MatchScoreForm';
import SelectCaipanForm from './components/SelectCaipanForm';
import { tableChangePagination } from './components/Pagination';

import styles from './TableList.less';
import { isNull } from 'util';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ zubie, gameList, place, score, loading }) => ({
  zubie,
  gameList,
  place,
  score,
  loading: loading.models.zubie,
}))
@Form.create()
export default class MatchView extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    zubieBGColor: {},
    zubieTextColor: {},
    curData: {},
    modalVisible: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });

    dispatch({
      type: 'zubie/clean',
      payload: {},
    });

    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        // this.props.dispatch({
        //   type: 'zubie/queryZhixu',
        //   payload: {
        //     gameId: id,
        //   },
        // });
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback: () => {
            let zubieBGColor = {};
            let zubieTextColor = {};
            const colors = [
              '#290C44',
              '#ECF10E',
              '#ED06A7',
              '#0AF506',
              '#06BEBC',
              '#1890FF',
              'red',
              'yellow',
              'black',
              'orange',
              'pink',
            ];
            const textColors = [
              'white',
              'green',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
            ];
            this.props.zubie.zubieList.forEach((element, index) => {
              if (element.enabled) {
                zubieBGColor[element.code] = colors[index];
                zubieTextColor[element.code] = textColors[index];
              }
            });
            this.setState({ zubieBGColor: zubieBGColor });
            this.setState({ zubieTextColor: zubieTextColor });
            this.props.dispatch({
              type: 'place/findPlaceData',
              payload: { gameId: id },
            });

            // this.props.dispatch({
            //   type: 'zubie/queryFanganHeader',
            //   payload: {
            //     gameId: id,
            //   },
            //   callback: ()=> {
            //     this.props.dispatch({
            //       type: 'zubie/queryFangan',
            //       payload: {
            //         gameId: id,
            //       }
            //     })
            //   },
            // })
            this.props.dispatch({
              type: 'place/findPlaceForGame',
            });
            this.props.dispatch({
              type: 'place/findGameCaipan',
              payload: {},
            });
          },
        });
      },
    });
  }

  addNewChangxu = () => {
    message.warn('功能暂未实现');
  };

  generateJiemuMap = () => {
    var jiemuMap = {};
    this.props.zubie.zhixuList.list &&
      this.props.zubie.zhixuList.list.map(element => {
        jiemuMap[element.bisaiId] = element;
      });
    return jiemuMap;
  };

  showItemMenu = item => {
    return (
      <Menu>
        <Menu.Item>
          <Popconfirm
            title="是否确定添加新的场次，后面的场次会以此往后移？ "
            onConfirm={() => this.addNewChangxu(item)}
            okText="Yes"
            cancelText="No"
          >
            <Button>添加新场次</Button>
          </Popconfirm>
        </Menu.Item>
      </Menu>
    );
  };

  showScoreModel = item => {
    this.props.dispatch({
      type: 'score/findScores',
      payload: item.code,
      callback: () => {
        this.setState({ curData: item, modalVisible: true, scoreList: this.props.score.scoreList });
      },
    });
  };

  showGameMenu = item => {
    console.log(item);
    return (
      <Menu>
        <Menu.Item onClick={() => this.showScoreModel(item)}>
          <Icon type="snippets" />
          成绩录入
        </Menu.Item>
        <Menu.Item
          onClick={() => {
            this.showCaipanSelectModal(item.code);
          }}
        >
          <Icon type="user" />
          指定裁判
        </Menu.Item>
        <Menu.Item
          key="jifen"
          onClick={() => window.open('/bgms/gameScore/jifenbiao/' + item.code, 'GET')}
        >
          <Icon type="file-text" />
          下载记分表
        </Menu.Item>
        <Menu.Item key="video" onClick={() => message.warn('开发中')}>
          <Icon type="video-camera" />
          投屏显示
        </Menu.Item>
      </Menu>
    );
  };

  renderJiemu = item => (
    <Dropdown overlay={this.showGameMenu(item)} trigger={['contextMenu']} placement="bottomCenter">
      <div
        draggable={true}
        onDragStart={e => this.startDrag(e, item)}
        onDrop={e => this.dropDrag(e, item.zubiePlaceCode, item.placeCode, item)}
        onDragOver={e => this.dragDragOver(e)}
        style={{
          textAlign: 'center',
          backgroundColor: this.state.zubieBGColor[item.zubieCode],
          color: this.state.zubieTextColor[item.zubieCode],
        }}
      >
        <div
          style={{
            borderStyle: 'none none solid none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.bisaiId}
        </div>
        <div>
          {' '}
          {item.zubieName}({item.projectCode})
        </div>
        <div>
          {' '}
          {item.phaseName} 第{item.round}轮
        </div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid none none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.gamePosName1}
          </span>
          <span style={{ flex: 1 }}>{item.gamePosName2}</span>
        </div>
        {this.renderJiemuAthlete(item)}
        <div style={{ display: 'flex' }}>
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.team1}
          </span>
          <span style={{ flex: 1 }}>{item.team2}</span>
        </div>
      </div>
    </Dropdown>
  );

  renderJiemuAthlete = item => {
    const userList1 = item.athlethList1.map((value, index, array) => {
      return value.userName;
    });

    const userList2 = item.athlethList2.map((value, index, array) => {
      return value.userName;
    });
    return (
      <div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid none solid none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <div
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {userList1.join(',')}
          </div>
          <div style={{ flex: 1 }}>{userList2.join(',')}</div>
        </div>
      </div>
    );
  };

  startDrag = (e, item) => {
    e.dataTransfer.setData('item', JSON.stringify(item)); // 拖拽元素携带的数据
  };

  dropDrag = (e, zubiePlaceCode, placeCode, curItem) => {
    e.preventDefault();
    const itemData = JSON.parse(e.dataTransfer.getData('item'));

    if (curItem) {
      if (curItem.id === itemData.id) {
        return;
      }
      this.props.dispatch({
        type: 'zubie/jiaohuanChangxu',
        payload: {
          matchId1: curItem.id,
          placeCode1: itemData.placeCode,
          zubiePlaceCode1: itemData.zubiePlaceCode,
          matchId2: itemData.id,
          placeCode2: placeCode,
          zubiePlaceCode2: zubiePlaceCode,
        },
        callback: () => {
          message.success('设置成功');
          this.props.dispatch({
            type: 'place/findPlaceData',
            payload: { gameId: this.state.id },
          });

          this.props.dispatch({
            type: 'zubie/queryNotSetPlaceGame',
            payload: {
              gameId: this.state.id,
            },
          });
        },
      });
    } else {
      this.props.dispatch({
        type: 'zubie/setKongchang',
        payload: {
          id: itemData.id,
          placeCode: placeCode,
          zubiePlaceCode: zubiePlaceCode,
        },
        callback: () => {
          message.success('设置成功');
          this.props.dispatch({
            type: 'place/findPlaceData',
            payload: { gameId: this.state.id },
          });

          this.props.dispatch({
            type: 'zubie/queryNotSetPlaceGame',
            payload: {
              gameId: this.state.id,
            },
          });
        },
      });
    }
  };

  dragDragOver = e => {
    e.preventDefault(); // 此处的代码是必须的  不然无法拖拽
    //e.target.style.backgroundColor='black'
    //console.log(e.target.backgroundColor)
  };

  handleMatchScoreModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      scoreList: [],
      curData: {},
    });
  };

  modifyScore = (item, callback) => {
    this.props.dispatch({
      type: 'score/modifyScore',
      payload: item,
      callback: () => {
        message.success('成绩修改成功');
        this.props.dispatch({
          type: 'score/findScores',
          payload: item.bisaiCode,
          callback: () => {
            this.setState({ scoreList: this.props.score.scoreList });
          },
        });
      },
    });
  };

  listDataChange = list => {
    this.setState({ scoreList: list });
  };

  render() {
    const {
      zubie: { curZubieObj, zhixuList, fanganHeader, fanganList, notSetPlaceGameList },
      loading,
      place: { placeList, placeData, caipanList, matchCaipanList },
    } = this.props;

    matchCaipanList &&
      caipanList &&
      matchCaipanList.forEach(item => {
        caipanList.forEach(caipan => {
          if (caipan.code === item.caipanCode) {
            caipan.caipanRole = item.caipanRole;
          }
        });
      });

    const { caipanSelectModalVisible } = this.state;

    const caipanSelectMethod = {
      handleAdd: this.caipanSelectHandler,
      handleModalVisible: this.caipanSelectHandleModalVisible,
    };

    const jiemuChangdi = [];

    placeList.map(value => {
      jiemuChangdi.push({
        title: value.name,
        dataIndex: value.code,
        align: 'center',
        render: (item, row) => {
          if (item) {
            return this.renderJiemu(item, row);
          } else {
            return (
              <div
                style={{ width: 150, height: 100 }}
                onDrop={e => this.dropDrag(e, row.code, value.code)}
                onDragOver={e => this.dragDragOver(e)}
              />
            );
          }
        },
      });
    });

    const columnJiemu = [
      {
        title: '日期',
        dataIndex: 'matchDate',
        width: 90,
        render: value => <span>{value.substring(5, 10)}</span>,
      },
      {
        title: '时间段',
        dataIndex: 'timePhase',
        width: 60,
        render: value => {
          switch (value) {
            case 'morning':
              return '上午';
            case 'afternoon':
              return '下午';
            case 'night':
              return '晚上';
          }
        },
      },
      {
        title: '场序',
        dataIndex: 'seq',
        width: 50,
        render: (text, record) => (
          <Dropdown
            overlay={this.showItemMenu(record)}
            trigger={['contextMenu']}
            placement="bottomCenter"
          >
            <div style={{ width: 30 }}>{text}</div>
          </Dropdown>
        ),
      },
      {
        title: '场  地  名  称',
        children: jiemuChangdi,
      },
    ];

    const comparePhase = (obj2, obj1) => {
      var val1 = obj1.phaseSeq;
      var val2 = obj2.phaseSeq;
      var val3 = obj1.round;
      var val4 = obj2.round;
      var val5 = obj1.fenzuName;
      var val6 = obj2.fenzuName;
      var val7 = obj1.id;
      var val8 = obj2.id;
      if (val1 < val2) {
        return 1;
      } else if (val1 > val2) {
        return -1;
      } else {
        if (val3 < val4) {
          return 1;
        } else if (val3 > val4) {
          return -1;
        } else {
          if (val5 < val6) {
            return 1;
          } else if (val5 > val6) {
            return -1;
          } else {
            if (val7 < val8) {
              return 1;
            } else if (val7 > val8) {
              return -1;
            } else {
              return 0;
            }
          }
        }
      }
    };

    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
            <Table
              size="small"
              loading={loading}
              pagination={false}
              bordered
              dataSource={placeData}
              columns={columnJiemu}
              style={{ flex: 1, marginRight: 10 }}
              scroll={{ y: 500 }}
            />
          </div>
        </Card>

        <MatchScoreForm
          modalVisible={this.state.modalVisible}
          modifyMatch={this.state.curData}
          value={this.state.scoreList}
          onChange={this.listDataChange}
          updateScore={this.modifyScore}
          close={() => this.setState({ modalVisible: false })}
        />

        <SelectCaipanForm
          {...caipanSelectMethod}
          modalVisible={caipanSelectModalVisible}
          caipanList={caipanList ? caipanList : []}
        />
      </Fragment>
    );
  }

  showCaipanSelectModal = matchCode => {
    this.props.dispatch({
      type: 'place/queryMatchCaipan',
      payload: {
        matchCode: matchCode,
      },
      callback: () => {
        this.setState({
          caipanSelectModalVisible: true,
          matchCode,
        });
      },
    });
  };

  caipanSelectHandler = values => {
    this.props.dispatch({
      type: 'place/setCaipan',
      payload: {
        matchCode: this.state.matchCode,
        caipanCode: values.code,
        caipanRole: values.caipanRole,
      },
      callback: () => {
        message.success('设置成功');
        this.props.dispatch({
          type: 'place/queryMatchCaipan',
          payload: {
            matchCode: this.state.matchCode,
          },
        });
      },
    });
  };

  caipanSelectHandleModalVisible = flag => {
    this.setState({
      caipanSelectModalVisible: !!flag,
    });
  };
}
